import { login, sysProfile, sysUser } from '@/api/user'
import { getToken, setToken } from '@/utils/auth'
import asyncRoutes from '@/router/modules/index'
import roter from '@/router'
import { constantRoutes } from '@/router'
import { resetRouter } from '@/router'

const state = {
  token: getToken() || '',
  userInfo: ''
}
const mutations = {
  setToken(state, value) {
    state.token = value
    setToken(value)
  },
  setUserInfo(state, value) {
    state.userInfo = value
  },
  logout(state) {
    state.token = ''
    setToken('')
    state.userInfo = ''
    resetRouter()
  }
}
const actions = {
  // 登陆调用
  async toLogin({ commit }, value) {
    // login(value)
    //   .then((res) => {
    //     console.log('res', res)
    //     commit('setToken', res.data)
    //   })
    //   .catch((err) => {
    //     console.log('err', err)
    //   })
    const res = await login(value)
    commit('setToken', res.data)
    console.log(res)
  },
  async getUserInfo({ commit, state }) {
    const res = await sysProfile()
    const res2 = await sysUser(res.data.userId)
    commit('setUserInfo', { ...res.data, ...res2.data })
    // console.log(res, res2)

    const newArr = asyncRoutes.filter((item) => {
      return state.userInfo.roles.menus.includes(item.name)
    })
    // 添加的路由不能立马使用，会匹配到404，将404匹配路由动态添加
    newArr.push({ path: '*', redirect: '/404', hidden: true })
    // 将匹配项添加到路由配置中，router.addRoutes（【路由配置】），添加新的路由配置
    roter.addRoutes(newArr)
    commit('routes/setRoutesList', [...constantRoutes, ...newArr], {
      root: true
    })
  }
}
const getters = {}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
